import logging

import coloredlogs


class CustomLoggerAdapter(logging.LoggerAdapter):
    FORMAT = "%(asctime)s %(filename)s:%(lineno)d in %(funcName)s\n" \
             "[%(levelname)s] [%(country)s] [%(doc_type)s] %(message)s"

    def __init__(self, logger, country_name, doc_type):
        super().__init__(logger, {})
        self.logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter(self.FORMAT)
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

        coloredlogs.install(level='DEBUG', logger=self.logger, fmt=self.FORMAT,
                            field_styles={'levelname': {'bold': True, 'color': 'white'},
                                          'filename': {'bold': False, 'color': 'white', 'faint': True},
                                          'lineno': {'bold': False, 'color': 'white', 'faint': True},
                                          'funcName': {'bold': False, 'color': 'white', 'faint': True},
                                          'asctime': {'color': 'green'},
                                          'country': {'color': 'magenta'},
                                          'doc_type': {'color': 'magenta'}},
                            level_styles={'info': {'color': 'green'}, 'debug': {'color': 'blue'},
                                          'error': {'color': 'red'}},
                            )
        self.extra['country'] = country_name
        self.extra['doc_type'] = doc_type

    def process(self, msg, kwargs):
        extra = {}
        if 'extra' in kwargs:
            extra = kwargs.pop('extra')
        extra.update(self.extra)
        kwargs['extra'] = extra
        return msg, kwargs
